import { motion, AnimatePresence } from "motion/react";
import { useState, useRef, useEffect, useCallback } from "react";
import {
  Send,
  Paperclip,
  Mic,
  Square,
  Command as CommandIcon,
  CircleStop,
  Sparkles,
  Image as ImageIcon,
  FileText,
  Code,
  CornerDownLeft,
  ArrowUp,
  X,
  Bot,
  Globe
} from "lucide-react";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "./ui/tooltip";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import { ModelSelector } from "./ModelSelector";

interface InputAreaProps {
  inputText: string;
  isTyping: boolean;
  onInputChange: (text: string) => void;
  onSubmit: (e: React.FormEvent) => void;
  inputRef: React.RefObject<HTMLTextAreaElement>;
  onStopGeneration?: () => void;
}

const commandList = [
  { value: "ai-chat", label: "AI Chat", icon: Bot },
  { value: "web-search", label: "Web Search", icon: Globe },
  { value: "code-gen", label: "Code Generation", icon: Code },
  { value: "image-gen", label: "Image Generation", icon: ImageIcon },
];

export function InputArea({
  inputText,
  isTyping,
  onInputChange,
  onSubmit,
  inputRef,
  onStopGeneration,
}: InputAreaProps) {
  const [isRecording, setIsRecording] = useState(false);
  const [showAttachmentMenu, setShowAttachmentMenu] = useState(false);
  const [showCommandMenu, setShowCommandMenu] = useState(false);
  const [textareaHeight, setTextareaHeight] = useState(56);
  const [isMobile, setIsMobile] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const attachmentMenuRef = useRef<HTMLDivElement>(null);

  // 检测是否为移动端
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth < 768);
    };

    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);

    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 自动调整文本框高度
  const adjustTextareaHeight = useCallback(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      const newHeight = Math.min(textareaRef.current.scrollHeight, isMobile ? 150 : 200);
      textareaRef.current.style.height = `${newHeight}px`;
      setTextareaHeight(newHeight);
    }
  }, [isMobile]);

  useEffect(() => {
    adjustTextareaHeight();
  }, [inputText, adjustTextareaHeight]);

  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const text = e.target.value;
    onInputChange(text);

    if (text.endsWith('@')) {
      setShowCommandMenu(true);
    } else if (showCommandMenu && !text.includes('@')) {
      setShowCommandMenu(false);
    }
  };

  const handleCommandSelect = (value: string) => {
    const newText = inputText.substring(0, inputText.lastIndexOf('@')) + `/${value} `;
    onInputChange(newText);
    setShowCommandMenu(false);
    textareaRef.current?.focus();
  };

  // 处理键盘快捷键
  const handleKeyDown = (e: React.KeyboardEvent) => {
    // 移动端不处理快捷键
    if (isMobile) return;

    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (inputText.trim() && !isTyping) {
        onSubmit(e);
      }
    }

    // Ctrl/Cmd + Enter 发送消息
    if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
      e.preventDefault();
      if (inputText.trim() && !isTyping) {
        onSubmit(e);
      }
    }
  };

  // 处理录音
  const toggleRecording = () => {
    if (isRecording) {
      setIsRecording(false);
      // 这里可以添加停止录音的逻辑
    } else {
      setIsRecording(true);
      // 这里可以添加开始录音的逻辑
    }
  };

  // 附件选项
  const attachmentOptions = [
    { icon: ImageIcon, label: "图片", type: "image" },
    { icon: FileText, label: "文档", type: "document" },
    { icon: Code, label: "代码", type: "code" },
  ];

  // 点击外部关闭附件菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (attachmentMenuRef.current && !attachmentMenuRef.current.contains(event.target as Node)) {
        setShowAttachmentMenu(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  return (
    <motion.div
      initial={{ y: 20, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      className="p-3 md:p-4 bg-gradient-to-t from-white/60 to-white/40 dark:from-slate-900/60 dark:to-slate-800/40 backdrop-blur-xl border-t border-white/20 dark:border-slate-700/30"
    >
      <div className="max-w-4xl mx-auto">
        <div className="flex justify-start mb-3 px-3">
          <ModelSelector />
        </div>
        {/* 快捷键提示 - 仅桌面端显示 */}
        {!isMobile && (
          <div className="flex items-center justify-between mb-2 md:mb-3 px-2">
            <div className="flex items-center gap-2 md:gap-4 text-xs text-slate-500 dark:text-slate-400">
              <div className="flex items-center gap-1">
                <CommandIcon className="w-3 h-3" />
                <CornerDownLeft className="w-3 h-3" />
                <span>发送</span>
              </div>
              <div className="flex items-center gap-1">
                <ArrowUp className="w-3 h-3" />
                <CornerDownLeft className="w-3 h-3" />
                <span>换行</span>
              </div>
            </div>

            {/* 字数统计 */}
            {inputText.length > 0 && (
              <Badge variant="outline" className="text-xs">
                {inputText.length} 字符
              </Badge>
            )}
          </div>
        )}

        <form onSubmit={onSubmit} className="relative">
          {/* 附件菜单 */}
          <AnimatePresence>
            {showAttachmentMenu && (
              <motion.div
                ref={attachmentMenuRef}
                initial={{ opacity: 0, scale: 0.95, y: 10 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95, y: 10 }}
                className="absolute bottom-full left-0 md:left-4 mb-2 bg-white dark:bg-slate-800 rounded-xl shadow-xl border border-slate-200 dark:border-slate-700 p-2 z-50"
              >
                {/* 移动端关闭按钮 */}
                {isMobile && (
                  <button
                    type="button"
                    onClick={() => setShowAttachmentMenu(false)}
                    className="absolute top-2 right-2 p-1 rounded-full hover:bg-slate-100 dark:hover:bg-slate-700"
                  >
                    <X className="w-4 h-4 text-slate-500" />
                  </button>
                )}

                <div className="grid grid-cols-3 gap-2 mt-6 md:mt-0">
                  {attachmentOptions.map((option) => (
                    <TooltipProvider key={option.type}>
                      <Tooltip>
                        <TooltipTrigger asChild>
                          <motion.button
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                            className="p-2 md:p-3 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors flex flex-col items-center"
                            onClick={() => {
                              // 处理附件选择
                              setShowAttachmentMenu(false);
                            }}
                          >
                            <option.icon className="w-5 h-5 text-slate-600 dark:text-slate-300" />
                            <span className="text-xs mt-1 text-slate-600 dark:text-slate-300">{option.label}</span>
                          </motion.button>
                        </TooltipTrigger>
                        <TooltipContent>
                          <p>{option.label}</p>
                        </TooltipContent>
                      </Tooltip>
                    </TooltipProvider>
                  ))}
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* 输入区域 */}
          <Popover open={showCommandMenu} onOpenChange={setShowCommandMenu}>
            <PopoverTrigger asChild>
              <div className="relative flex items-end gap-2 md:gap-3 bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-lg hover:shadow-xl transition-shadow">
                {/* 附件按钮 */}
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        type="button"
                        variant="outline"
                        onClick={() => setShowAttachmentMenu(!showAttachmentMenu)}
                        className="m-2 text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200"
                        disabled={isTyping}
                      >
                        <Paperclip className="w-4 h-4 md:w-5 md:h-5" />
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>添加附件</p>
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>

                {/* 文本输入框 */}
                <div className="flex-1 min-w-0">
                  <textarea
                    ref={(el) => {
                      if (el) {
                        textareaRef.current = el;
                        if (inputRef) {
                          // @ts-ignore
                          inputRef.current = el;
                        }
                      }
                    }}
                    value={inputText}
                    onChange={handleInputChange}
                    onKeyDown={handleKeyDown}
                    placeholder={isMobile ? "输入消息..." : "输入消息或使用 @ 选择工具"}
                    disabled={isTyping}
                    className="w-full px-2 py-2 md:px-2 md:py-3 bg-transparent text-slate-900 dark:text-slate-100 placeholder-slate-400 dark:placeholder-slate-500 resize-none outline-none text-sm md:text-base leading-relaxed"
                    style={{ height: `${textareaHeight}px`, maxHeight: isMobile ? '150px' : '200px' }}
                    rows={1}
                  />
                </div>

                {/* 右侧按钮组 */}
                <div className="flex items-center gap-1 md:gap-2 m-2">
                  {/* 录音按钮 */}
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          type="button"
                          variant="outline"
                          onClick={toggleRecording}
                          className={`text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-200 ${isRecording ? 'text-red-500 hover:text-red-600' : ''
                            }`}
                          disabled={isTyping}
                        >
                          <motion.div
                            animate={isRecording ? { scale: [1, 1.1, 1] } : {}}
                            transition={{ duration: 1, repeat: isRecording ? Infinity : 0 }}
                          >
                            {isRecording ? (
                              <Square className="w-4 h-4 md:w-5 md:h-5" />
                            ) : (
                              <Mic className="w-4 h-4 md:w-5 md:h-5" />
                            )}
                          </motion.div>
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>{isRecording ? '停止录音' : '开始录音'}</p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>

                  {/* 发送/停止按钮 */}
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          type={isTyping ? "button" : "submit"}
                          disabled={(!inputText.trim() && !isTyping) || isRecording}
                          onClick={isTyping ? onStopGeneration : undefined}
                          className={`${isTyping
                            ? 'bg-red-500 hover:bg-red-600 text-white'
                            : 'bg-blue-500 hover:bg-blue-600 text-white'
                            } shadow-lg hover:shadow-xl transition-all h-8 w-8 md:h-10 md:w-10 p-0`}
                        >
                          <motion.div
                            whileHover={{ scale: 1.1 }}
                            whileTap={{ scale: 0.9 }}
                          >
                            {isTyping ? (
                              <CircleStop className="w-4 h-4 md:w-5 md:h-5" />
                            ) : (
                              <Send className="w-4 h-4 md:w-5 md:h-5" />
                            )}
                          </motion.div>
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>{isTyping ? '停止生成' : '发送消息'}</p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </div>
              </div>
            </PopoverTrigger>
            <PopoverContent className="w-80 p-0" side="top" align="start">
              <Command>
                <CommandInput placeholder="搜索指令..." />
                <CommandList>
                  <CommandEmpty>未找到指令。</CommandEmpty>
                  <CommandGroup heading="指令">
                    {commandList.map((command) => (
                      <CommandItem
                        key={command.value}
                        value={command.value}
                        onSelect={handleCommandSelect}
                      >
                        <command.icon className="mr-2 h-4 w-4" />
                        <span>{command.label}</span>
                      </CommandItem>
                    ))}
                  </CommandGroup>
                </CommandList>
              </Command>
            </PopoverContent>
          </Popover>

          {/* AI能力提示 - 仅桌面端显示 */}
          {!isMobile && (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              className="mt-2 md:mt-3 flex items-center justify-center gap-1 md:gap-2 text-xs text-slate-500 dark:text-slate-400"
            >
              <Sparkles className="w-3 h-3" />
              <span>支持代码高亮 • 表格解析 • 图像识别 • 文档处理</span>
            </motion.div>
          )}
        </form>
      </div>
    </motion.div>
  );
}
